package com.gblfy.lyrabbitmq.consumer;

import com.gblfy.lyrabbitmq.consts.MQPrefixConst;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;


/**
 * RabbitMQ消费端处理
 *
 * @author gblfy
 * @Date 2021-09-28 9:59
 */
@Component
public class RabbitMQHandler implements ChannelAwareMessageListener {
    //打印日志 实时定位
    private final static Logger log = LoggerFactory.getLogger(RabbitMQHandler.class);

    /**
     * 接收字符串类型MQ消息
     *
     * @param message
     * @param channel
     * @throws Exception
     */
    @Override
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${spring.rabbitmq.listener.str1.queue.name}",
                    durable = "${spring.rabbitmq.listener.str1.queue.durable}"),
            exchange = @Exchange(value = "${spring.rabbitmq.listener.str1.exchange.name}",
                    durable = "${spring.rabbitmq.listener.str1.exchange.durable}",
                    type = "${spring.rabbitmq.listener.str1.exchange.type}",
                    ignoreDeclarationExceptions = "${spring.rabbitmq.listener.str1.exchange.ignoreDeclarationExceptions}"),
            key = "${spring.rabbitmq.listener.str1.key}"
    )
    )
    @RabbitHandler
    public void onMessage(Message message, Channel channel) throws Exception {

        //TODO 接收消息成功 创建一个消费端轨迹表来存储消息的轨迹数据
        String jsonMsg = new String(message.getBody());
        log.info("响应报文 mResXml: {}", jsonMsg);

        // 同一时刻服务器只会发一条消息给消费者
        channel.basicQos(1);
        // 反馈消息的消费状态
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        // 反馈消息的消费状态System.err.println("--------------------------------------");


        //------------------------------根据约定解析指定的标签--------------------------------------------
        // JSONObject jsonObject = new JSONObject();
        // jsonObject = JSON.parseObject(jsonMsg);

        // String msgID = jsonObject.getString("msgID");
        // log.info("接收的消息ID: {}", msgID);
        //
        // String tResXml = jsonObject.getString("tResXml");
        // log.info("解析后的zip路径: {}", tResXml);

        String queueRouteKey = message.getMessageProperties().getReceivedRoutingKey();
        log.info("接收的路由key: {}", queueRouteKey);

        if (MQPrefixConst.LY_MQ_FAI_QUERY.equals(queueRouteKey)) {
            //TODO  监听查询接口逻辑

            //TODO 保存数据到数据库
        } else {
            log.error("无此路由key: {}", queueRouteKey);
        }
    }
}


